import json

import shortuuid

from mall.models.brand import Brand
from mall.models.metadata import Metadata
from mall.models.product import Product, ProductCategory, ProductContent, ProductMetadata
from mall.models.resource import Resource


def init_product_data(engine):
    print(Brand.__table__.insert())

    conn = engine.connect()
    for r in ('KOKIA_09.png', 'KOKIA_03.png', 'KOKIA_07.png'):
        conn.execute(Resource.__table__.insert(),
                     id=shortuuid.uuid(),
                     origin_file_name=r,
                     mime_type='image/jpeg',
                     path=r,
                     thumb_path=r)
    from sqlalchemy.sql import select
    resource_list = conn.execute(select([Resource.__table__]))

    resource_ids = [r[0] for r in resource_list]
    print(resource_ids)
    for r in resource_list:
        print(r)
    # 产品分类
    product_category_table = ProductCategory.__table__
    conn.execute(product_category_table.insert(), id='game', screen_name='Game')

    # 产品元数据
    game_type_extension = [{
        'code': 'RPG',
        'screen_name': '角色扮演',
    }, {
        'code': 'simulation',
        'screen_name': '模拟经营',
    }, {
        'code': 'adventure and decryption',
        'screen_name': '冒险解密',
    }, {
        'code': 'STG',
        'screen_name': '动作射击',
    }, {
        'code': 'Strategic',
        'screen_name': '策略益智',
    }, {
        'code': 'Sports and Music',
        'screen_name': '休闲体育音乐',
    }]

    metadata_table = Metadata.__table__
    conn.execute(
        metadata_table.insert(),
        {
            'id': 'game-platform',
            'screen_name': '激活平台',
            'type': 'game',
            'value_mode': 'muti-select',
            'extension': '[{"code":"PSN","screen_name":"PSN"},{"code":"Xbox","screen_name":"XBOX"}]',
        },
        {
            'id': 'game-language',
            'screen_name': '支持语言',
            'type': 'game',
            'value_mode': 'muti-select',
            'extension': '[{"code":"zh_CN","screen_name":"中国大陆"},{"code":"us","screen_name":"美国"}]',
        },
        {
            'id': 'game-area',
            'screen_name': '有效区域',
            'type': 'game',
            'value_mode': 'muti-select',
            'extension': '[{"code":"zh","screen_name":"中国大陆"},{"code":"us","screen_name":"美国"},{"code":"eu","screen_name":"欧洲"}]',
        },
        {
            'id': 'game-publish-date',
            'screen_name': '发布日期',
            'type': 'game',
            'value_mode': 'text',
            'extension': '',
        },
        {
            'id': 'game-type',
            'screen_name': '游戏类型',
            'type': 'game',
            'value_mode': 'muti-select',
            'extension': json.dumps(game_type_extension),
        },
    )
    # 商品
    import random
    for p in ['魔兽世界',
              '权利的游戏',
              '上古卷轴5',
              '彩虹6号:围攻',
              '超级塞亚人',
              '吃怪兽，打豆豆',
              '传奇',
              '天下3',
              '守望先锋',
              '精灵宝可梦GO',
              '剑网3',
              '穿越火线',
              '梦幻西游',
              '地下城与勇士']:
        _id = shortuuid.uuid()
        minimum_price = random.randrange(1, 20)
        maximum_price = random.randrange(21, 50)
        conn.execute(Product.__table__.insert(),
                     id=_id,
                     title=p,
                     sub_title='{}副标题'.format(p),
                     type='normal',
                     click_count=random.randrange(1, 100),
                     collection_count=random.randrange(1, 500),
                     category_id='game',
                     minimum_price=minimum_price,
                     maximum_price=maximum_price,
                     average_price=(minimum_price + maximum_price) / 2,
                     cover_resource_id=random.choice(resource_ids)

                     )
        conn.execute(ProductContent.__table__.insert(),
                     language_code='zh_CN',
                     product_id=_id,
                     summary='{} 是一未XX的游戏，这是{} 的简要描述'.format(p, p),
                     detail='<p><这里是{}的详细描述/p>'.format(p)
                     )
        result = conn.execute(select([Metadata.__table__]))
        for row in result:
            id = row[Metadata.__table__.c.id]
            value_mode = row[Metadata.__table__.c.value_mode]
            extension = row[Metadata.__table__.c.extension]
            screen_name = row[Metadata.__table__.c.screen_name]

            if value_mode == 'muti-select':
                extension = json.loads(extension)
                print(extension)

                count = random.randrange(1, len(extension))

                conn.execute(
                    ProductMetadata.__table__.insert(),
                    product_id=_id,
                    name=screen_name,
                    metadata_id=id,
                    value=','.join(e['code'] for e in extension[0:count])
                )
            if value_mode == 'text':
                conn.execute(
                    ProductMetadata.__table__.insert(),
                    product_id=_id,
                    name=screen_name,
                    metadata_id=id,
                    value='2015-{}-{}'.format(random.randint(1, 12), random.randint(1, 31))
                )
    # print(Brand.c)
        # pass
        # print(resource_list)
        # print(Brand.c)
#         # pass
# def init_product_data1(session):
#     for r in ('KOKIA_09.png', 'KOKIA_03.png', 'KOKIA_07.png'):
#         re = Resource(
#             id=shortuuid.uuid(),
#             origin_file_name=r,
#             mime_type='image/jpeg',
#             path=r,
#             thumb_path=r,
#         )
#         session.add(re)
#         session.commit()
#     resource_list =  session.query(Resource).all()
#     category = ProductCategory(
#         screen_name='Game',
#         id='game'
#     )
#     game_type_extension = [{
#         'code': 'RPG',
#         'screen_name': '角色扮演',
#     }, {
#         'code': 'simulation',
#         'screen_name': '模拟经营',
#     }, {
#         'code': 'adventure and decryption',
#         'screen_name': '冒险解密',
#     }, {
#         'code': 'STG',
#         'screen_name': '动作射击',
#     }, {
#         'code': 'Strategic',
#         'screen_name': '策略益智',
#     }, {
#         'code': 'Sports and Music',
#         'screen_name': '休闲体育音乐',
#     }]
#
#     session.add(category)
#     session.commit()
#
#     meta1 = Metadata()
#     meta1.id = 'game-platform'
#     meta1.screen_name = '激活平台'
#     meta1.type = category.id
#     meta1.value_mode = 'muti-select'
#     meta1.extension = '[{"code":"PSN","screen_name":"PSN"},{"code":"Xbox","screen_name":"XBOX"}]'
#     meta1.product_category = category
#     meta2 = Metadata()
#     meta2.id = 'game-language'
#     meta2.screen_name = "支持语言"
#     meta2.type = category.id
#     meta2.value_mode = 'muti-select'
#     meta2.product_category = category
#     meta2.extension = '[{"code":"zh_CN","screen_name":"中国大陆"},{"code":"us","screen_name":"美国"}]'
#     meta3 = Metadata()
#     meta3.id = 'game-area'
#     meta3.type = category.id
#     meta3.screen_name = "有效区域"
#     meta3.value_mode = 'muti-select'
#     meta3.product_category = category
#     meta3.extension = '[{"code":"zh","screen_name":"中国大陆"},{"code":"us","screen_name":"美国"},{"code":"eu","screen_name":"欧洲"}]'
#     meta4 = Metadata()
#     meta4.type = category.id
#     meta4.id = 'game-publish-date'
#     meta4.screen_name = "发布日期"
#     meta4.value_mode = 'text'
#     meta4.product_category = category
#
#     meta5 = Metadata()
#     meta5.id = 'game-type'
#     meta5.type = category.id
#     meta5.screen_name = '游戏类型'
#     meta5.value_mode = 'muti-select'
#     meta5.extension = json.dumps(game_type_extension)
#     for m in [meta1, meta2, meta3, meta4,meta5]:
#         session.add(m)
#     session.commit()
#     import random
#     for p in ['魔兽世界',
#               '权利的游戏',
#               '上古卷轴5',
#               '彩虹6号:围攻',
#               '超级塞亚人',
#               '吃怪兽，打豆豆',
#               '传奇',
#               '天下3',
#               '守望先锋',
#               '精灵宝可梦GO',
#               '剑网3',
#               '穿越火线',
#               '梦幻西游',
#               '地下城与勇士']:
#         _id = shortuuid.uuid()
#         brand = Brand()
#         product = Product()
#         product.id = _id
#         product.title = p
#         product.sub_title = '{} 的副标题'.format(p)
#         product.type = 'normal'
#         product.click_count = random.randint(0, 1000)
#         product.collection_count = random.randint(0, 500)
#         product.category = category
#         product.like_count = random.randint(0, 400)
#         product.minimum_price = random.randint(0,55)
#         product.maximum_price = random.randint(60,200)
#         product.average_price = (product.minimum_price + product.maximum_price ) /2
#         product.cover_resource_id = random.choice(resource_list).id
#         product.brand_id = brand.id
#         # product.cover = 'http://oc3dkgv4l.bkt.clouddn.com/{}'.format(
#         # random.choice(['KOKIA_09.png', 'KOKIA_03.png', 'KOKIA_07.png']))
#
#         product.contents.append(ProductContent(
#             language_code='zh_CN',
#             product_id=_id,
#             summary='这是{} 的简要描述'.format(p),
#             detail='这是 {} 的详情'.format(p)
#
#         ))
#
#         platform = (
#             'PSN',
#             'Steam',
#             '{"code": "Stream","value": "Stream"}'
#         )
#         session.add(product)
#         for metadata in session.query(Metadata).all():
#             if metadata.id == 'game-platform':
#                 session.add(
#                     ProductMetadata(
#                         product_id=_id,
#                         name=metadata.screen_name,
#                         metadata_id=metadata.id,
#                         value=random.choice(platform)
#                     )
#                 )
#             if metadata.id == 'game-area':
#                 session.add(
#                     ProductMetadata(
#                         product_id=_id,
#                         name=metadata.screen_name,
#                         metadata_id=metadata.id,
#                         value='{"code":"eu","value":"欧洲"}'
#                     )
#                 )
#             if metadata.id == 'game-publish-date':
#                 session.add(
#                     ProductMetadata(
#                         product_id=_id,
#                         name=metadata.screen_name,
#                         metadata_id=metadata.id,
#                         value='2015-{}-{}'.format(random.randint(1, 12), random.randint(1, 31))
#                     )
#                 )
#             if metadata.id == 'game-language':
#                 session.add(
#                     ProductMetadata(
#                         product_id=_id,
#                         name=metadata.screen_name,
#                         metadata_id=metadata.id,
#                         value='{"code":"zh_CN","value":"简体中文"}'
#                     )
#                 )
#             if metadata.id == 'game-type':
#                 count = random.choice((1, 2, 3, 4, 5, 6))
#                 metadata_value = []
#                 for c in range(0,count):
#                     metadata_value.append(game_type_extension[c - 1]['code'])
#
#                 session.add(
#                     ProductMetadata(
#                         product_id=_id,
#                         name=metadata.screen_name,
#                         metadata_id=metadata.id,
#                         value='2015-{}-{}'.format(random.randint(1, 12), random.randint(1, 31))
#                     )
#                 )
#         session.commit()
